package com.wuhunyu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wuhunyu.commonutils.check.Check;
import com.wuhunyu.commonutils.result.CommonResult;
import com.wuhunyu.entities.EduChapter;
import com.wuhunyu.entities.EduVideo;
import com.wuhunyu.entities.vo.ChapterVo;
import com.wuhunyu.mapper.EduChapterMapper;
import com.wuhunyu.mapper.EduCourseMapper;
import com.wuhunyu.mapper.EduVideoMapper;
import com.wuhunyu.service.EduChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuhunyu.servicebase.exception.Assert;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author wuhunyu
 * @since 2021-01-17
 */
@Service("eduChapterService")
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {

    @Resource
    private EduCourseMapper eduCourseMapper;

    @Resource
    private EduChapterMapper eduChapterMapper;

    @Resource
    private EduVideoMapper eduVideoMapper;

    @Override
    public CommonResult selectChapters(String courseId) {
        // 校验参数
        Assert.isRight(Check.isBlank(courseId), "课程id不能为空");
        // 查询课程是否存在
        Assert.isRight(Check.isBlank(eduCourseMapper.selectById(courseId)), "查询课程信息不存在");
        // 查询出所有的章节信息
        QueryWrapper<EduChapter> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.select("id", "title","sort");
        queryWrapper1.eq("course_id", courseId);
        queryWrapper1.orderByAsc("sort");
        // 查询章节信息
        List<EduChapter> eduChapters = eduChapterMapper.selectList(queryWrapper1);

        // 查询所有的小节信息
        QueryWrapper<EduVideo> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.select("id", "title", "chapter_id", "sort", "is_free", "video_source_id", "video_original_name");
        queryWrapper2.eq("course_id", courseId);
        queryWrapper2.orderByAsc("sort");
        // 查询小节信息
        List<EduVideo> eduVideos = eduVideoMapper.selectList(queryWrapper2);

        // 封装结果
        ArrayList<ChapterVo> chapterVos1 = new ArrayList<>();
        eduChapters.forEach(eduChapter -> {
            // 章节信息转换
            ChapterVo chapterVo = new ChapterVo(eduChapter.getId(), eduChapter.getTitle(), eduChapter.getSort(), 0, null, null, null, null);
            chapterVos1.add(chapterVo);
            // 小节信息转换
            ArrayList<ChapterVo> chapterVos2 = new ArrayList<>();
            eduVideos.forEach(video -> {
                if (chapterVo.getId().equals(video.getChapterId())) {
                    chapterVos2.add(new ChapterVo(video.getId(), video.getTitle(), video.getSort(), 1, video.getIsFree(), video.getVideoSourceId(), video.getVideoOriginalName()));
                }
            });
            chapterVo.setChildren(chapterVos2);
        });

        // 封装结果集
        Map<String, Object> map = new HashMap<>(16);
        map.put("chapters", chapterVos1);
        return CommonResult.success("查询课程信息成功", map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult addChapter(EduChapter eduChapter) {
        // 校验参数
        // 章节对象非空
        Assert.isRight(Check.isBlank(eduChapter), "章节对象不能为空");
        // 课程id不能为空
        Assert.isRight(Check.isBlank(eduChapter.getCourseId()), "课程id不能为空");
        // 标题不能为空
        Assert.isRight(Check.isBlank(eduChapter.getTitle()), "章节标题不能为空");
        // 章节排序
        Assert.isRight(eduChapter.getSort() == null || eduChapter.getSort() < 0, "章节排序不合法");
        // 校验课程是否存在
        Assert.isRight(Check.isBlank(eduCourseMapper.selectById(eduChapter.getCourseId())), "章节所在课程不存在");
        // 校验章节，排序是否唯一
        QueryWrapper<EduChapter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", eduChapter.getCourseId());
        List<EduChapter> eduChapters = eduChapterMapper.selectList(queryWrapper);
        eduChapters.forEach(chapter -> {
            if (eduChapter.getTitle().equals(chapter.getTitle())) {
                Assert.isRight(true, "章节标题已存在");
            }
            if (eduChapter.getSort().equals(chapter.getSort())) {
                Assert.isRight(true, "排序已存在");
            }
        });
        // 执行插入操作
        Assert.isRight(eduChapterMapper.insert(eduChapter) != 1, "章节新增失败");
        return CommonResult.success("章节新增成功");
    }

    @Override
    public CommonResult selectChapterById(String id) {
        // 校验参数
        Assert.isRight(Check.isBlank(id), "章节id不能为空");
        // 执行查询操作
        EduChapter eduChapter = eduChapterMapper.selectById(id);
        Assert.isRight(Check.isBlank(eduChapter), "查询的章节不存在");
        // 封装结果集
        Map<String, Object> map = new HashMap<>(16);
        map.put("chapter", map);
        return CommonResult.success("查询章节成功", map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult updateChapter(EduChapter eduChapter) {
        // 校验参数
        // 章节对象非空
        Assert.isRight(Check.isBlank(eduChapter), "章节对象不能为空");
        // 章节id不能为空
        Assert.isRight(Check.isBlank(eduChapter.getId()), "章节id不能为空");
        // 课程id不能为空
        Assert.isRight(Check.isBlank(eduChapter.getCourseId()), "课程id不能为空");
        // 标题不能为空
        Assert.isRight(Check.isBlank(eduChapter.getTitle()), "章节标题不能为空");
        // 章节排序
        Assert.isRight(eduChapter.getSort() == null || eduChapter.getSort() < 0, "章节排序不合法");
        // 校验课程是否存在
        Assert.isRight(Check.isBlank(eduCourseMapper.selectById(eduChapter.getCourseId())), "章节所在课程不存在");
        // 章节是否存在
        Assert.isRight(Check.isBlank(eduChapterMapper.selectById(eduChapter.getId())), "章节不存在");
        // 校验章节，排序是否唯一
        QueryWrapper<EduChapter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", eduChapter.getCourseId());
        List<EduChapter> eduChapters = eduChapterMapper.selectList(queryWrapper);
        eduChapters.forEach(chapter -> {
            if (eduChapter.getTitle().equals(chapter.getTitle()) && !eduChapter.getId().equals(chapter.getId())) {
                Assert.isRight(true, "章节标题已存在");
            }
            if (eduChapter.getSort().equals(chapter.getSort()) && !eduChapter.getId().equals(chapter.getId())) {
                Assert.isRight(true, "排序已存在");
            }
        });
        // 执行更新操作
        Assert.isRight(eduChapterMapper.updateById(eduChapter) < 0, "章节修改失败");
        return CommonResult.success("章节修改成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult deleteChapterById(String id) {
        // 参数校验
        // 章节id不能为空
        Assert.isRight(Check.isBlank(id), "章节id不能为空");
        // 章节是否存在
        Assert.isRight(Check.isBlank(eduChapterMapper.selectById(id)), "章节不存在");
        // 查看章节是否拥有小节
        QueryWrapper<EduVideo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("chapter_id", id);
        Assert.isRight(eduVideoMapper.selectCount(queryWrapper) > 0, "章节存在小节，无法删除");
        // 执行删除操作
        Assert.isRight(eduChapterMapper.deleteById(id) !=1, "章节删除失败");
        return CommonResult.success("章节删除成功");
    }

}
